﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Input;
using MasterDetailTemplate.Models;
using MasterDetailTemplate.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Xamarin.Forms;

namespace MasterDetailTemplate.ViewModels
{
    public class AnniversaryChangePageViewModel : ViewModelBase
    {
        /******** 构造函数 ********/

        private IEventStorage _eventStorage;
        private IContentNavigationService _contentNavigationService;

        public AnniversaryChangePageViewModel(IEventStorage eventStorage,
            IContentNavigationService contentNavigationService)
        {
            _eventStorage = eventStorage;
            _contentNavigationService = contentNavigationService;
        }

        public Event Event
        {
            get => _event;
            set => Set(nameof(Event), ref _event, value);
        }

        private Event _event;

        public bool IsImportant
        {
            get => _isImportant;
            set => Set(nameof(IsImportant), ref _isImportant, value);
        }

        private bool _isImportant;

        public string Att
        {
            get => _att;
            set => Set(nameof(Att), ref _att, value);
        }

        private string _att;

        /******** 绑定命令 ********/

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        private RelayCommand _pageAppearingCommand;

        /// <summary>
        /// 页面显示命令。
        /// </summary>
        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand =
                new RelayCommand(async () =>
                {
                    await PageAppearingCommandFunction();
                }));

        public async Task PageAppearingCommandFunction()
        {
            Att = Event.Attribute.Equals(1) ? "纪念日" : "倒数日";
            IsImportant = Event.IsImportant.Equals(1) ? true : false;
        }


        public ICommand SaveCommand =>
            _saveCommand ?? (_saveCommand = 
                new Command(async () => 
                    await SaveCommandFunction()));

        private ICommand _saveCommand;

        public async Task SaveCommandFunction()
        {
            Event.IsImportant = IsImportant ? 1 : 0;
            Event.DateStamp = DateTime.Now.Ticks;
            await _eventStorage.SaveEventAsync(Event);
            await _contentNavigationService.GoBackAsync();
        }

        public ICommand CancelCommand =>
            _cancelCommand ?? (_cancelCommand = 
                new Command(async () => 
                    await CancelCommandFunction()));

        private ICommand _cancelCommand;

        public async Task CancelCommandFunction()
        {
            await _contentNavigationService.GoBackAsync();
        }
    }
}
